package com.lxj.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lxj
 * @date 2021/7/30 18:13
 * @Description: feign的拦截
 */
@Configuration
public class FeignInterceptor implements RequestInterceptor {


    /**
     * feign的拦截方法
     * 3种场景需要使用这个feign的拦截器传递token
     * 1.前端------>A------->B   (正常的用户token)
     * 2.Mq-------->B   (是我们应用的token)
     * 3.支付宝回调----->(放行)A------>B (是我们应用的token)
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if(!ObjectUtils.isEmpty(requestAttributes)){
            // 1或者3场景
            HttpServletRequest request = requestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");
            if(!StringUtils.hasText(authorization)){
                //第1种场景，直接传递
                requestTemplate.header("Authorization",authorization);
                return;
            }
        }
        // 说明是2和3场景 给一个应用的token
        requestTemplate.header("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJ3cml0ZSJdLCJleHAiOjM3NzUzNzIyMDksImp0aSI6IjY0OWRjOGQxLTM1YWQtNDZlOC05NzQxLTVhN2U3ODg5MjlhMSIsImNsaWVudF9pZCI6ImNsaWVudCJ9.fDpDOk6scgf-imC6tYwZYXjTi-1xzRZmVvk6pAQazo2fEq5yN20TgeHhzWxBVzMv6BKW2HHCF5pkpSmun-iWIMROab9VAAn_wWJD5qRRhH335-DUBkvABhOHG-TzeZJG0e7ooeNdQ7nY79dK3JIqOnZrGe-arBWn0ztVE71bqmQiOz0-cmYh-NmYK_S-ek08H82DCc0t6G3-lhlj_JaJCq0VcaW7vPhpg4944vS63cM_1cW6k4jEEUP8T8jfM7NVHWqya_30_JspCXTzVIDX9M6A5Xnck6jXpPBLbmoAxciLcXM3mh_tWeXGiFDssqB9dKGnds6o8b_o9NkplxK2Qw");
    }
}
